package com.adream.scalpel.app.server.service;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.adream.scalpel.app.client.service.UserManagement;
import com.adream.scalpel.common.client.vo.UserVO;
import com.adream.scalpel.common.server.domain.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class UserManagementImpl extends RemoteServiceServlet implements UserManagement {

    private PersistenceManagerFactory pmf;

    @Override
    public void addUser(UserVO userVo) {
        PersistenceManager pm = pmf.getPersistenceManager();
        try {
            User user = new User(userVo.getUserName());
            user.setFirstName(userVo.getFirstName());
            user.setLastName(userVo.getLastName());
            user.setDisplayName(userVo.getDisplayName());
            user.setAddress1(userVo.getAddress1());
            user.setAddress2(userVo.getAddress2());
            user.setAddress3(userVo.getAddress3());
            user.setPassword(userVo.getPassword());
            user.setEnabled(userVo.getEnabled());
            pm.makePersistent(user);
        } finally {
            pm.close();
        }
    }

    @SuppressWarnings("unchecked")
    public ArrayList<UserVO> searchUserByDisplayName(String userNameSearchString) {
        ArrayList<UserVO> usersVO = new ArrayList<UserVO>();

        PersistenceManager pm = pmf.getPersistenceManager();
        Query query = pm.newQuery(User.class);
        query.setFilter("displayName == displayNameParam");
        query.declareParameters("String displayNameParam");

        try {
            List<User> users = (List<User>) query.execute(userNameSearchString);

            for (User user : users) {
                usersVO
                        .add(new UserVO(user.getUserName(), user.getFirstName(), user.getLastName(), user
                                .getDisplayName(), user.getAddress1(), user.getAddress2(), user.getAddress3(), user
                                .isEnabled()));
            }
            return usersVO;
        } finally {
            query.closeAll();
        }
    }

    public void setPmf(PersistenceManagerFactory pmf) {
        this.pmf = pmf;
    }

    public void updateUser(UserVO userVo) {
        PersistenceManager pm = pmf.getPersistenceManager();
        try {
            User user = pm.getObjectById(User.class, userVo.getUserName());
            user.setFirstName(userVo.getFirstName());
            user.setLastName(userVo.getLastName());
            user.setDisplayName(userVo.getDisplayName());
            user.setAddress1(userVo.getAddress1());
            user.setAddress2(userVo.getAddress2());
            user.setAddress3(userVo.getAddress3());
        } finally {
            pm.close();
        }
    }
}
